package com.one.apartmentsystem.app.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayDataDataserviceBillDownloadurlQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.one.apartmentsystem.app.domain.PaymentManage;
import com.one.apartmentsystem.app.domain.PaymentRecord;
import com.one.apartmentsystem.app.domain.PropertyItem;
import com.one.apartmentsystem.app.service.AlipayService;
import com.one.apartmentsystem.app.service.PaymentManageService;
import com.one.apartmentsystem.app.service.PaymentRecordService;
import com.one.apartmentsystem.app.service.PropertyItemService;
import com.one.apartmentsystem.common.properties.AliPayProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author Sakura
 * @Date 9/9/2019
 **/
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private AliPayProperties aliPayProperties;

    @Autowired
    private PaymentManageService paymentManageService;

    @Autowired
    private PropertyItemService propertyItemService;

    @Autowired
    private PaymentRecordService paymentRecordService;

    @Override
    public String create(String orderId ) {
        // 获取缴费信息
        PaymentManage paymentManage = paymentManageService.getById(orderId);
        // 获取缴费项信息
        PropertyItem propertyItem = propertyItemService.getById(paymentManage.getType());
        AlipayClient alipayClient;
        try {
            alipayClient = new DefaultAlipayClient(alipayConfig);

        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(aliPayProperties.getNotifyUrl());
        request.setReturnUrl(aliPayProperties.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        // 订单信息
        bizContent.put("out_trade_no", paymentManage.getManageId());
        // 缴费金额
        if(propertyItem.getType()==1){
            bizContent.put("total_amount", propertyItem.getPrice()*paymentManage.getDosage());
        }else if (propertyItem.getType()==2) {
            bizContent.put("total_amount", propertyItem.getPrice());
        }

        // 缴费项名称
        bizContent.put("subject", propertyItem.getName());
        // 卖家支付宝用户ID
        bizContent.put("seller_id", "2088721040912668");

        request.setBizContent(bizContent.toString());

        AlipayTradeWapPayResponse response;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();

        if (response.isSuccess()) {

            return pageRedirectionData;
        } else {
            return null;
        }
    }

    @Override
    public void notify(HttpServletRequest request) {

        Map<String, String> map = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }
        //验证签名
        boolean signVerified;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), alipayConfig.getSignType());
        } catch (com.alipay.api.AlipayApiException e) {
            log.info("[支付验证] 异常={}", JSONUtil.parse(e));
            return;
        }
        if (signVerified) {
            //TODO 判断是支付还是退款 来修改payment_record表中的值


                PaymentRecord paymentRecord = new PaymentRecord();
                PaymentManage paymentManage = paymentManageService.getById(Integer.valueOf(map.get("out_trade_no")));
                paymentRecord.setPaymentType(paymentManage.getType());
                paymentRecord.setCreateDate(new Date());
                paymentRecord.setPaymentId(paymentManage.getManageId());
                paymentRecordService.save(paymentRecord);


        }


    }

    @Override
    public void refund(String orderId) {
        AlipayClient client = null;
        try {
            client = new DefaultAlipayClient(alipayConfig);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        AlipayTradeRefundRequest alipay_request = new AlipayTradeRefundRequest();

        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        //退款的订单Id，也可以设置流水号
        model.setOutTradeNo(orderId);
        // 获取缴费信息
        PaymentManage paymentManage = paymentManageService.getById(orderId);
        // 获取缴费项信息
        PropertyItem propertyItem = propertyItemService.getById(paymentManage.getType());
        //退款金额
        //==1代表按量交付
        if(propertyItem.getType()==1)
        {
            model.setRefundAmount(String.valueOf(paymentManage.getDosage()*propertyItem.getPrice()));
        }
        //==1代表一次性交付
        else if((propertyItem.getType()==2))
        {
            model.setRefundAmount(String.valueOf(propertyItem.getPrice()));
        }

        alipay_request.setBizModel(model);
        String alipay_response = "";
        try {
            alipay_response = client.execute(alipay_request).getBody();
        } catch (AlipayApiException e) {
            log.info("【支付宝支付】退款失败 error={}", e);
        }
        log.info("[支付退款] response={}", alipay_response);
    }

    @Override
    public String bill() {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            AlipayDataDataserviceBillDownloadurlQueryModel model = new AlipayDataDataserviceBillDownloadurlQueryModel();
//            model.setSmid("2088123412341234");
            model.setBillType("trade");
            model.setBillDate("2024-08-18");
            request.setBizModel(model);
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            return  response.getBody();
//            if (response.isSuccess()) {
//                System.out.println("调用成功");
//            } else {
//                System.out.println("调用失败");
//                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
//                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
//                // System.out.println(diagnosisUrl);
//            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


    }
}